package com.css.devops.service.jenkins;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import com.css.devops.component.JenkinsBasicComponent;
import com.css.devops.constants.DevopsConstants;
import com.css.devops.utils.JsonMapperUtils;
import com.fasterxml.jackson.databind.JsonNode;

import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class JenkinsJobBuildManagerService {

	@Autowired
    private JenkinsBasicComponent jenkinsBasicComponent;
    
    /**
     * 使用 HTTP 请求将 Job 添加到 View 中
     * @param viewName
     * @param jobName
     */
	public void jobBuildDetails(String jobName,String branchName) {
        try {
        	String endPoint = String.format(DevopsConstants.JENKINS_JOB_BUILD_DETAILS, jobName, branchName);
        	HttpResponse response = jenkinsBasicComponent.getRequest(endPoint);
        	// 检查响应码
            int responseCode = response.getStatus();
            if (responseCode == HttpStatus.OK.value()) {
            	JsonNode builds = JsonMapperUtils.getInstance().readTree(response.body());
            	builds.forEach(node->{
            		String id = node.get("id").asText();
            		String name = node.get("name").asText();
            		String status = node.get("status").asText();
            		long durationInMillis = node.path("durationInMillis").asLong();
            		long startTimeMillis = node.path("startTimeMillis").asLong();
            		long endTimeMillis = node.path("endTimeMillis").asLong();
                    
            		System.out.println(name);
            		System.out.println(id);
            		System.out.println(status);
            		System.out.println(durationInMillis);
            		System.out.println(startTimeMillis);
            		System.out.println(endTimeMillis);
            	});
            } else {
                System.out.println("Failed  " + responseCode);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
